﻿using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NlpTrainApp.Model;

namespace NlpTrainAppWebapiTestsIntegration
{
    public class HubMessageClient
    {
        public string Key { get; set; }
        /// <summary>
        /// 消息处理事件
        /// </summary>
        public event EventHandler<HubMessageModel> MessageDeal;

        public HubConnection Connection { get; set; }
        private readonly ILogger<HubMessageClient> logger;
        public HubMessageClient(ILogger<HubMessageClient> logger)
        {
            this.logger = logger;
        }
        public async Task<bool> StartConnect(string url)
        {
            Connection = new HubConnectionBuilder()
                           .WithUrl(url)
                           .Build();

            Connection.On<HubMessageModel>("ReceiveMessage", (message) =>
                    MessageDeal?.Invoke(this, message)
            );
            Connection.Closed += Connection_Closed;

            try
            {
                await Connection.StartAsync();
                return true;
            }
            catch
            {
                logger?.LogError($"连接{url}错误");
                return false;
            }
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="connectionId"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessage(HubMessageModel message)
        {
            try
            {
                await Connection.SendAsync("ReceiveMessage", Connection.ConnectionId, message);
                //await Connection.InvokeAsync("ReceiveMessage", Connection.ConnectionId, message);//
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, $"{Key}发送消息错误：{JsonConvert.SerializeObject(message)}");
            }
        }
        private async Task Connection_Closed(Exception arg)
        {
            //关了需要检测服务端，然后自动重连
            try
            {
                if (arg != null)
                {
                    logger?.LogError(arg, "连接异常关闭");
                }
                await Connection.StartAsync();
            }
            catch
            {
                logger?.LogError("重新连接错误");
            }
        }

    }
}

